using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Caliburn.Micro;
using MediaOwl.Common;
using MediaOwl.Common.Logging;
using MediaOwl.Common.ScreenManagement;

namespace MediaOwl
{
    public class AppBootstrapper : Bootstrapper<IShell>
    {
        private CompositionContainer container;

        [Export]
        public static AggregateCatalog Catalog { get; private set; }

        public AppBootstrapper()
        {
#if DEBUG

            Application.Current.UnhandledException += (s, e) =>
            {
                throw e.ExceptionObject;
            };

#endif

            LogManager.GetLog = type => new DebugLog(type);
            ApplyCustomConventions();
        }

        private static void ApplyCustomConventions()
        {
            ConventionManager.AddElementConvention<NumericUpDown>(
                NumericUpDown.ValueProperty,
                "Value",
                "ValueChanged");
        }

        protected override void Configure()
        {
            AssemblySource.Instance.Add(typeof (Show).Assembly);

            Catalog = new AggregateCatalog(
                AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()
                );

            container = CompositionHost.Initialize(Catalog);

            var batch = new CompositionBatch();

            batch.AddExportedValue<IWindowManager>(new WindowManager());
            batch.AddExportedValue<IEventAggregator>(new EventAggregator());
            batch.AddExportedValue(container);

            container.Compose(batch);
        }

        protected override object GetInstance(Type serviceType, string key)
        {
            string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
            var exports = container.GetExportedValues<object>(contract);

            if (exports.Count() > 0)
                return exports.First();

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }

        protected override IEnumerable<object> GetAllInstances(Type serviceType)
        {
            return container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
        }

        protected override void BuildUp(object instance)
        {
            container.SatisfyImportsOnce(instance);
        }
    }
}